package com.nkym.wypan.aspect;

import com.nkym.wypan.enums.ResponseStatus;
import com.nkym.wypan.exception.BusinessException;
import com.nkym.wypan.utils.JwtUtils;
import com.nkym.wypan.utils.ShareContextHolder;
import com.nkym.wypan.utils.UserContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/*
 * @ClassName CheckShareCodeAspect
 * @Author nkym
 * @Date 2023/8/17 17:48
 * @Version 1.0
 */
@Component
@Aspect
public class CheckShareCodeAspect {

    private static final String SHARE_TOKEN = "share-token";

    @Pointcut("@annotation(com.nkym.wypan.annotation.CheckShareCode)")
    public void pointcut() {
    }


    @Before("pointcut()")
    public void before(JoinPoint jp) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String shareToken = request.getHeader(SHARE_TOKEN);
        Long shareId = JwtUtils.getShareIdOrNull(shareToken);
        if (shareId==null){
            throw  new BusinessException(ResponseStatus.VERIFY_CODE_INVALID);
        }
        ShareContextHolder.setId(shareId);
    }

}
